package com.xwb.laboratory.test.cglib;

import java.lang.reflect.Method;

import com.xwb.laboratory.test.proxy.Programmer;
import com.xwb.laboratory.test.proxy.ProgrammerX;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

public class CglibDemo {

	public String test1() {
		//被代理的对象
		ProgrammerX x = new ProgrammerX();
		
		//要增强的功能
		MethodInterceptor i = new MethodInterceptor() {
			@Override
			public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
				String s1 = "心情很好\n";
				String s2 = "\n代码写的漂亮";
				String r = (String) method.invoke(x, args);
				return s1 + r + s2;
			}
		};
		
		//CGLIB的增强器，即代理人
		Enhancer e = new Enhancer();
		e.setCallback(i);
		
		//代理接口
		e.setInterfaces(new Class[] {Programmer.class});
		Programmer p = (Programmer) e.create();
		String code = p.code();
		
		//代理类
		e.setSuperclass(ProgrammerX.class);
		e.setInterfaces(null);//经测试，同时代理接口和类也可以
		ProgrammerX x2 = (ProgrammerX) e.create();
		code = x2.code();
		
		return code;
	}
	
	public static void main(String[] args) {
		CglibDemo cd = new CglibDemo();
		System.out.println(cd.test1());
	}
}
